package hashTable;

import java.util.HashSet;
import java.util.Set;

/**
 * 给定两个数组，编写一个函数来计算它们的交集
 */
public class N349_IntersectionOfTwoArrays {
    public int[] intersection(int[] nums1, int[] nums2) {
        // 将某一nums数组去重
        Set<Integer> set1 = new HashSet<>();
        // 结果set
        Set<Integer> set2 = new HashSet<>();
        // nums1数组全部加入set1
        for (int i : nums1)
            set1.add(i);
        // 判断nums2的每个元素是否出现在num1中，出现过则加入set2
        for (int i : nums2) {
            if (set1.contains(i)) {
                set2.add(i);
            }
        }
        int index = 0;
        int[] arr = new int[set2.size()];
        for (Integer i : set2)
            arr[index++] = i;
        return arr;
    }

    public static void main(String[] args) {
        N349_IntersectionOfTwoArrays solution = new N349_IntersectionOfTwoArrays();
        int[] num1 = {1, 2, 2, 1, 3, 4, 5, 6, 7}, num2 = {1, 3, 11};
        int[] arr = solution.intersection(num1, num2);
        for (int i : arr) {
            System.out.print(i + "\t");
        }
    }
}
